/*
 * Copyright 2011 group coding kata nantes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.coding.kata.nantes.roman.stephane;

import org.apache.commons.lang.StringUtils;

import fr.coding.kata.nantes.roman.commons.NumeralsToRomanInterface;

public class NumeralsToRoman implements NumeralsToRomanInterface {

	private int valeur;
    
    
    @Override
    public NumeralsToRomanInterface with(final Integer numerals) {
    	valeur = numerals.intValue();
        return this;
    }

    @Override
    public String call() {
    	final StringBuilder sb = new StringBuilder();
    	extractDigits(valeur, 1, sb);
        return sb.toString();
    }

    private int extractDigits(final int num, final int rang, final StringBuilder sb) {
    	if(num / 10 > 0) {
    		extractDigits(num / 10, rang * 10, sb);
        }
    	final PuissancesDeDix pudd = PuissancesDeDix.ENUMS_DD.get(rang);
    	calcValeur(num % 10, pudd, sb);
        return rang;
    }
    
    private void calcValeur(final int chiffre, final PuissancesDeDix puissancesDeDix, final StringBuilder sb) {
    	if (chiffre > 9 || chiffre < 0) {
    		throw new IllegalArgumentException("Le chiffre ne peut etre superieur a 9 ou inferieur a 0");
    	} else if (chiffre == 0) {
    		// Nothing to do
    	} else if (chiffre == 4) {
    		sb.append(puissancesDeDix.increment);
    		sb.append(puissancesDeDix.secondaire);
    	} else if (chiffre == 9) {
    		sb.append(puissancesDeDix.increment);
    		sb.append(puissancesDeDix.principal);
    	} else if (chiffre < 4) {
    		sb.append(StringUtils.repeat(puissancesDeDix.increment, chiffre));
    	} else {
    		sb.append(puissancesDeDix.secondaire);
    		sb.append(StringUtils.repeat(puissancesDeDix.increment, chiffre - 5));
    	}
    }
    
}
